/* global window */
import pathToRegexp from 'path-to-regexp'
import modelExtend from 'dva-model-extend'
import { config } from 'utils'
import { list, remove } from 'services/entity'
import { message } from 'antd'
import { pageModel } from './common'



export default modelExtend(pageModel, {
  namespace: 'entity',

  state: {
    parentId: '',
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((pathname) => {
        const match = pathToRegexp('/entity/:id').exec(pathname.pathname)
        if (match) {
          dispatch({ type: 'list', payload: { id: match[1] } })
        }
      })
    },
  },

  effects: {
    * list ({ payload = {} }, { call, put }) {
      const data = yield call(list, payload)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            parentId: payload.id,
            list: data.data,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.total,
            },
          },
        })
      }
    },

    * delete ({ payload }, { call, put, select }) {
      const data = yield call(remove, { id: payload })
      const { selectedRowKeys } = yield select(_ => _.entity)
      if (data.success) {
        message.success('delete success')
        yield put({ type: 'updateState', payload: { selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload) } })
        yield put({ type: 'list' })
      } else {
        message.error('delete failed')
        throw data
      }
    },

  },

  reducers: {
  },
})
